package cn.t.web.user;

import cn.t.constants.ResponseError;
import cn.t.core.exception.BizException;
import cn.t.dto.user.ImportUserRequest;
import cn.t.facade.user.WrappedEnterpriseFacade;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelDataConvertException;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.List;

/**
 * @author l
 */
@Slf4j
@RestController
@RequestMapping("wrapped/enterprise")

@AllArgsConstructor
public class WrappedEnterpriseController {

    /**
     * Excel 导入用户
     */
    @PostMapping("/user/import")
    public void importUserInfo(@RequestParam(required = false) MultipartFile excel) {

        List<ImportUserRequest> excelDataList = null;

        String firmCode = "";

        try {
            byte[] data = excel.getBytes();
            excelDataList = EasyExcelFactory.read(new ByteArrayInputStream(data), new AnalysisEventListener<ImportUserRequest>() {
                @Override
                public void invoke(ImportUserRequest request, AnalysisContext analysisContext) {
                    List<String> results = wrappedEnterpriseFacade.validateImportUserRequest(firmCode, request);
                    if (!CollectionUtils.isEmpty(results)) {
                        StringBuilder errorMessage = new StringBuilder();
                        for (String str : results) {
                            errorMessage.append(str).append("\n");
                        }
                        throw new BizException(ResponseError.DATA_ERR, "格式错误：请检查第" + analysisContext.readRowHolder().getRowIndex() + "行数据。" + errorMessage.toString());
                    }
                }

                @Override
                public void onException(Exception exception, AnalysisContext context) {
                    // 如果异常是ExcelDataConvertException，则是格式错误
                    if (exception instanceof ExcelDataConvertException) {
                        throw new BizException(ResponseError.DATA_ERR, "格式错误：请检查第" + context.readRowHolder().getRowIndex() + "行数据。" + "行数据的格式是否正确。");
                    } else {
                        // 其他类型的异常
                        log.error("导入失败，失败原因：{}", exception.getMessage(), exception);
                    }
                }

                @Override
                public void doAfterAllAnalysed(AnalysisContext analysisContext) {

                }

            }).head(ImportUserRequest.class).ignoreEmptyRow(true).doReadAllSync();

        } catch (IOException e) {
            log.error("文件处理过程中IO 异常", e);
        }

        wrappedEnterpriseFacade.importUserInfo(excelDataList);
    }

    @Autowired
    private WrappedEnterpriseFacade wrappedEnterpriseFacade;

}
